package com.zqx.tokenauth.controller;

import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import com.zqx.tokenauth.auth.Authorization;
import com.zqx.tokenauth.auth.CurrentUser;
import com.zqx.tokenauth.entity.TokenModel;
import com.zqx.tokenauth.entity.User;
import com.zqx.tokenauth.enums.ResultEnum;
import com.zqx.tokenauth.repository.UserRepository;
import com.zqx.tokenauth.service.TokenManager;
import com.zqx.tokenauth.util.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;


/**
 * title:token controller
 * @author zqx
 * @date 2018.07.21
 */
@RestController
@RequestMapping("/tokens")
@Slf4j
public class TokenController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenManager tokenManager;

    @PostMapping("/login")
    public ResponseEntity login(@RequestParam String username, @RequestParam String password)
    {
        log.info("【登录方法】");
        Assert.notNull (username, "username can not be empty");
        Assert.notNull (password, "password can not be empty");
        User user = userRepository.findByUsername(username);
        // 未注册 或密码错误
        if (user == null || !user.getPassword ().equals (password)) {
            // 提示用户名或密码错误
            return new ResponseEntity (ResultVOUtil.error (ResultEnum.USERNAME_OR_PASSWORD_ERROR.getCode()), HttpStatus.NOT_FOUND);
        }
        TokenModel model = tokenManager.createToken(user.getId());
        return new ResponseEntity(ResultVOUtil.ok(model),HttpStatus.OK);
    }

    @DeleteMapping("/logout")
    @Authorization
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public ResponseEntity logout (@CurrentUser User user) {
        tokenManager.deleteToken (user.getId());
        return new ResponseEntity (ResultVOUtil.ok (), HttpStatus.OK);

    }

}


